#
#       GameTrailersHD
#		A boxee plugin to list movies from scenereleases.info
#		by riegersn
#
#       Copyright 'riegersn' 2008 BoxeeHQ.com
#
#		All my scripts are free to use and to change. I only ask that you credit
#		my work in anything you use this for. If its not your code, don't say it is.
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#
#		GameTrailers Menu Layout
#
#		hd
#		|_	video list
#
#		podcasts
#		|_	podcast feeds
#			|_	video list
#
#		screwattack
#		|_	video game vault
#			|_	list links
#				|_ video
#			top ten
#			|_	list links
#				|_ video
#			angry video game nerd
#			|_	list links
#				|_ video
#
#		retrospective
#		|_	game sections
#			|_ video list
#
#		gameheads
#		|_	video list

__plugin__ 	= "GameTrailers"
__author__ 	= "riegersn"
__url__ 	= "http://boxeehq.com"
__svn__ 	= "svn/trunk/plugins/video/GameTrailersHD/"
__version__ = "0.9"

import os, urllib, re, time, datetime
import xbmc, xbmcgui, xbmcplugin
import boxeehq_pytools as bhq

#grab to root directory and assign the image forlder a var
rootDir = os.getcwd()
if rootDir[-1] == ';':rootDir = rootDir[0:-1]
imageDir = os.path.join(rootDir, 'thumbnails') + '/'

class Thumbnails:
	def __init__( self ):
		self.default = ''

class gtMode:
	def __init__( self ):
		self.head = 1458
		self.hd = 8465
		self.rss = 4872
		self.retro = 4751
		self.screw = 2465
		self.search = 6184

img = Thumbnails()
modes = gtMode()

for image in os.listdir( imageDir ):
	base, ext = image.lower().split('.')
	if ext == 'png':
		setattr(img, base, imageDir+image)

_burl = 'http://gametrailers.com'

def _catsInitial():
	_adddir('GameHead', _burl+'/gamehead.php', modes.head, img.gamehead)
	_adddir('HD', 'gthdvideo', modes.hd, img.hd)
	_adddir('Podcasts', 'podcasts', modes.rss, img.rss)
	_adddir('Retrospectives', _burl+'/search.php?s=Retrospective&str_type=games&ac=1', modes.retro, img.retrospectives)
	_adddir('Screw Attack', _burl+'/screwattack.php', modes.screw, img.screwattack)
	_adddir('Search', _burl+'/search.php?s=', modes.search, img.search)

def _gthdvideo(url):
	if url == 'gthdvideo':
		_adddir('Trailers', _setlink('gthd.php?p={platform}&show=Trailers'), modes.hd, img.trailers)
		_adddir('Reviews', _setlink('gthd.php?p={platform}&show=Reviews'), modes.hd, img.reviews)
		_adddir('Gameplay', _setlink('gthd.php?p={platform}&show=Gameplay'), modes.hd, img.gameplay)
		_adddir('Interviews', _setlink('gthd.php?p={platform}&show=Interview'), modes.hd, img.interviews)
	elif 'gthd.php?p={platform}&show=' in url:
		html = bhq.getHTML(_burl+'/gthd.php')
		platforms = re.compile('<option value="(?!all)([^"]+).+?>([^<]+)<').findall(html)
		for section, title in platforms:
			_adddir( title, url.replace('{platform}', section), modes.hd, '%s%s.png' % ( imageDir, section ) )
	else:
		html = bhq.r_dict( bhq.getHTML(url), { '\n':'', '\t':'' } )

		try:
			next_link = re.compile('.+reviewlist_barlink reviewlist_barlink_gthd".+?href="(.+?)"').findall(html)[0]
			_adddir( '', _burl+'/gthd.php%s' % (next_link), 1 , '%snext.png' % (imageDir) )
		except: pass

		regx = 'movie_listing_row_gthd.+?player/([0-9]+).+?src="([^"]+).+?game_url.+?>(.+?)<.+?title_url.+?>(.+?)<.+?">(.+?)<.+?gthd">(.+?)<.+?Views:.(.+?)<.+?Rating:.(.+?)<.+?Votes:.(.+?)<'
		vids = re.compile(regx).findall( html )
		for link, thumb, game, video, date, plot, views, rating, votes in vids:
			try:
				_link = getGTRLink( _burl+'/player/%s.html' % (link) )
				_listinfo = {
					'Title' : '%s - %s' % (game, video),
					'Date' : str(time.strftime('%d-%m-%Y', time.strptime(date, '%b %d, %Y'))),
					'Plot' : plot.strip(),
					'Studio' : 'GameTrailers.com'
					}
				_addlink( _link, thumb, _listinfo )
			except: pass

def _podcasts(url):
	if url == 'podcasts':
		html = bhq.getHTML( _setlink('podcasts.php'), 'basicinfo_text">', '<div class="rightthin_content">' )
		regx = 'src="([^"]+?)".+\s.+?<B>([^<]+?)<.+?<br>[^<]+?<.+?href=.+?href="([^"]+)"'
		rss = re.compile( regx ).findall( html )
		for thumb, title, feed in rss:
			_adddir( title, feed, modes.rss, thumb )
	else:
		html = bhq.getHTML( _burl+'/%s' % (url) ).replace( '\n', '' )
		regx = '<title>([^<]+?)</.+?summary>([^<]+?)<.+?url="([^"]+?)".+?pubDate>([^<]+?)<.+?duration>([^<]+?)<'
		feed = re.compile( regx ).findall( html )
		for title, plot, link, date, duration in feed:
			date = bhq.r_fromlist( date, ['EST', 'EDT'], '' ).strip()
			_date = time.strptime(date, '%a, %d %b %Y %H:%M:%S')
			_date = str(time.strftime('%d-%m-%Y', _date))
			_listinfo = {
				'Title' : title,
				'Plot' : plot,
				'Studio' :
				'GameTrailers.com',
				'Date' : _date
				}
			_addlink( link, '', _listinfo )

def _retrospectives(url):
	if 'search.php?' in url:
		html = bhq.getHTML(url)
		html = bhq.r_fromlist(html, ['\n', '\t', '\r'], '')
		regx = 'content_row_super.+?href="([^"]+?)".+?src="([^"]+?)".+?<a.+?title">([^<]+?)<.+?Date:[^>]+?>([^<]+?)<'
		retro = re.compile( regx ).findall( html )
		for link, thumb, title, date in retro:
			try:
				_adddir(title, _setlink(link+'?show=Features'), 11, _setlink(thumb))
			except: pass
	else:
		html = bhq.getHTML(url)
		html = bhq.r_fromlist(html, ['\n', '\t', '\r'], '')
		regx = '<table width="100%">.+?src="([^"]+?)".+?href="([^"]+?)".+?row_title">([^<]+?)<.+?escription">([^<]+?)<'
		game = re.compile('GameTitleSizeNormal[^>]?>([^<]+?)<').findall(html)[0]
		retro = re.compile( regx ).findall( html )
		for thumb, link, title, plot in retro:
			try:
				link = getGTRLink( _setlink(link) )
				listinfo = {
					'Title' : '%s: %s' % (game, title),
					'Plot' : '%s - %s' % (title, plot),
					'Studio' : 'GameTrailers.com'
					}
				_addlink( _setlink(link), _setlink(thumb),  listinfo)
			except: pass

def _gameHeads(url):
	html = bhq.getHTML(url)
	html = bhq.r_fromlist(html, ['\n', '\t', '\r'], '')
	regx = 'gamehead_container.+?href="([^"]+?)".+?src="([^"]+?)".+?">([^<]+?)<.+?">([^<]+?)<.+?">([^<]+?)<'
	vids = re.compile( regx ).findall( html )
	for link, thumb, title, date, plot in vids:
		try:
			link = getGTRLink(_burl+link)
			_listinfo = {
				'Title' : '%s - %s' % (title, plot),
				'Plot' : '%s - %s' % (title, plot),
				'Studio' : 'GameHeads: GameTrailers.com'
				}
			_addlink( link, _burl+'%s' % (thumb), _listinfo )
		except: pass

def _searchGT(url):
	_str = _keyboard( '', 'GameTrailers' )
	url = '%s%s&str_type=movies&ac=1' % (url, _str.replace(' ','+'))
	html = bhq.r_fromlist( bhq.getHTML(url), ['\n', '\t', '\r'], '' )
	regx = 'thumb"><a href="[^"]+?"><img src="([^"]+?)".+?href="([^"]+?)".+?row_title"><[^>]+?>([^<]+?)<.+?<b>([^<]+?)</b>'
	_vids = re.compile( regx ).findall( html )

	try:
	    next_link = re.compile('<a class="reviewlist_barlink".+href="(.+?)">Next').findall(html)[0]
	    _adddir( '', _burl+'/search.php%s' % (next_link), 1 , img.next )
	except: pass

	for thumb, link, title, plot in _vids:
		try:
			_link = getGTRLink( _burl+'%s.html' % (link) )
			_listinfo = {
				'Title' : '%s - %s' % (title, plot),
				'Plot' : '%s - %s' % (title, plot),
				'Studio' : 'GameTrailers.com'
				}
			_addlink( _link, _burl+'%s' % (thumb), _listinfo )
		except: pass

def _screwAttack(url):
	if url.endswith('screwattack.php'):
		_adddir('Video Game Vault', 'screw:vault', 7 , '')
		_adddir('Top Ten', 'screw:topten', 7 , '')
		_adddir('Angry Video Game Nerd', 'screw:nerd', 7 , '')
		return 0
	elif url.startswith('screw:'):
		html = bhq.getHTML(_burl+'/screwattack.php')
		html = bhq.r_fromlist( html, ['\n', '\t', '\r'], '')
		regx = 'gamepage_content_row">.+?href="([^"]+?)".+?src="([^"]+?)".+?title">[^>]+?>([^<]+?)<.+?date">([^<]+?)<.+?text">([^<]+?)<'

		if url == 'screw:vault':
			_html = html.split( 'id="vault">' )[1]
		elif url == 'screw:topten':
			_html = html.split( 'id="top10">' )[1]
			_html = _html.split( 'id="vault">' )[0]
		elif url == 'screw:nerd':
			_html = html.split( 'id="nerd">' )[1]
			_html = _html.split( 'id="top10">' )[0]

		_vids = re.compile( regx ).findall( _html )
		for link, image, title, date, plot in _vids:
			_pass = str( [link, image, title, date, plot] )
			_adddir( title, _pass, 7 , image )
	else:
		_pass = eval( url )
		vid = getGTRLink( _burl+'%s' % (_pass[0]) )
		listinfo = { 'Title' : _pass[2], 'Plot' : _pass[4], 'Date' : _pass[3] }
		_addlink( vid, _pass[1], listinfo )

def getGTRLink(url):
	html = bhq.getHTML(url)
	try: return re.compile('href="([^"]+?\.wmv)"').findall(html)[0]
	except:
		try: return re.compile('href="([^"]+?\.mov)"').findall(html)[0]
		except: return 0

def _setlink(link):
	link = link.strip()
	if '://' in link:
		return link
	else:
		if link.startswith('/'):
			return _burl+link
		else:
			return _burl+'/'+link

def _addlink( _url, _thumb, _info, _type="Video"):
	ok=True
	liz=xbmcgui.ListItem( _info['Title'], iconImage="DefaultVideo.png", thumbnailImage= _thumb )
	liz.setInfo( type = _type, infoLabels = _info )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=_url,listitem=liz)
	return ok

def _adddir( name, url, mode, iconimage=''):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
	return ok

def _keyboard( default="", heading="", hidden=False ):
	keyboard = xbmc.Keyboard( default, heading, hidden )
	keyboard.doModal()
	if ( keyboard.isConfirmed() ):
		return unicode( keyboard.getText(), "utf-8" )
	return default

def _parameters():
	param=[]
	paramstring=sys.argv[2]
	if len(paramstring)>=2:
		params=sys.argv[2]
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

def pdebug( _name, _str ):
	print 'gt:debug:%s:: %s' % ( _name, _str )

#grab params and assign them if found
params = _parameters()
url=None
name=None
mode=None

try: url=urllib.unquote_plus(params["url"])
except: pass

try: name=urllib.unquote_plus(params["name"])
except: pass

try: mode=int(params["mode"])
except: pass

pdebug('mode', mode)
pdebug('name', name)
pdebug('url', url)

if mode==None or url==None or len(url)<1:
    _catsInitial()
elif mode == modes.screw:
	_screwAttack(url)
elif mode == modes.search:
	_searchGT(url)
elif mode == modes.head:
	_gameHeads(url)
elif mode == modes.retro:
	_retrospectives(url)
elif mode == modes.hd:
	_gthdvideo(url)
elif mode == modes.rss:
	_podcasts(url)

xbmcplugin.endOfDirectory(int(sys.argv[1]))
